import { asyncRoutes, constantRoutes } from '@/router'

/* eslint-disable */

/**
 * Use meta.role to determine if the current user has permission
 * @param routePath
 * @param route
 */
function hasPermission(routePath, route) {
  if (route.path) {
    return routePath.includes(route.path)
  } else {
    return true
  }
}
 
function hasExist (roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param routePath
 */
export function filterAsyncRoutes(routes, routePath) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(routePath, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, routePath)
      }
      res.push(tmp)
    }
  })

  return res
}



export function getSysRoutePath(sysResourceList) {
  const res = []
  sysResourceList.forEach(route => {
    if(route.url) {
      if(route.children && route.children.length) {
        const routePathList = getSysRoutePath(route.children)
        routePathList.forEach(v => {
          res.push(v)
        })
      }
      res.push(route.url)
    }
  })
  
  return res
}


const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, { roles, sysResourceList }) {
    return new Promise(resolve => {
      const routePath = getSysRoutePath(sysResourceList)
      console.log('%c 🥐 routePath: ', 'font-size:20px;background-color: #ED9EC7;color:#fff;', routePath);

      const  accessedRoutes = filterAsyncRoutes(asyncRoutes, routePath)
      
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
